var  currentPage = 1;
var pageSize = 10;
var simpleArticle="";
$(document).ready(function() {
  
getArticledtobyuserandpage();
//getllArticleSort();
//getAllSection();
});

function index(t){
	currentPage=t;
	getArticledtobyuserandpage()
	
}


//后一页
function nextPage(){
	currentPage=currentPage+1;
	if(currentPage>totalPage){
		currentPage = totalPage;
	}
	$('#tbody').html("");
	 getArticledtobyuserandpage()
}

//前一页
function previousPage(){
	currentPage=currentPage-1;
	if(currentPage<1){
		currentPage=1;
	}
	$('#tbody').html("");
	 getArticledtobyuserandpage()
}


function modifyContent(e){
	alert(e);
}

/**
 * 获取修改的值并提交
 */
 function submitChange(){
	 var updatearticleinfoURL =getContextPath()+"/article/updatearticleinfo";
	 var articleId = $('#articleName').attr('aId');
	 var articleName = $('#articleName').val();
	var sortArticleId =  $('#articleSort').find("option:selected").attr("value");
	var sectionId =  $('#section').find("option:selected").attr("value");
	//alert("articleSort:"+sortArticleId)
	var articleType =  $('#articleType').find("option:selected").attr("value");
	var articleUp =  $('#articleUp').find("option:selected").attr("value");
	var articleSupport=0;
	if($('#articleSupport').is(':checked')) {
	    // do something
		articleSupport=1;
	}	
	
	
	bootbox.confirm(
            {
                message: "确认要更新吗",
                buttons: {
                    confirm: {
                        label: '确认'
                    },
                    cancel: {
                        label: '取消'
                    }
                },
                callback: function (result) {
                    // 返回 true  或者false
                    if (result) {
                    	
						var fd = new FormData();
						fd.append('articleId', articleId);
						if($("#file").get(0).files[0]!=null){
					    fd.append('file',$("#file").get(0).files[0]);
						}
					    fd.append('articleName',articleName);
					    fd.append('sortArticleId',sortArticleId);
					    fd.append('sectionId',sectionId);
					    fd.append('articleSupport',articleSupport);
					    fd.append('articleUp', articleUp)
					    $.ajax({
					        url: updatearticleinfoURL,
					        type: 'POST',
					        datatype: 'json',
					        data: fd,
					        cache:false,
					        traditional: true,
					        contentType: false,
					        processData: false,
					        success: function (data) {
					        	alert('发表成功');
					        },
					        error: function () {
					        	alert('数据有错')
					        }
					    });
                        
                    } else {
                        bootbox.alert("cancel");
                    }
                }
            });
	
		
	
  
	
//	alert("articleName"+articleName)
//	alert("articleSort"+articleSort)
//	alert("articleType"+articleType)
//	alert("articleUp"+articleUp)
//	alert("articleSupport"+articleSupport)
	 
 }

/**
 * 获取单个文章要修改内容前
 */
function getSimpleArticle(e){
	var articleId = e.getAttribute("id");
	var getSimpleArticleURL = getContextPath() + "/article/getsimplearticle";
	var sortArticleId;
	
	$.ajax({
    url: getSimpleArticleURL,
    async : false, //设置成为 同步的 
    type: 'post',
    data: {"articleId": articleId},
  })
  .done(function(data) {
    console.log("success");

     simpleArticle = data;
    console.log(simpleArticle);
    var obj=eval("("+data+")"); //转换json
       article = obj.article;
      var articleName = article.articleName;
      var articleType = article.articleType; //文章模式
      var sortArticle = article.articleSort;//文章分类
      var articleUp = article.articleUp;
      var articleSupport = article.articleSupport;//作者推荐
      var articleId = article.articleId;
      var section = article.section;
      var cover = article.articleCover;
      //alert("section:" + section.sectionId);
      sortArticleId = sortArticle.sortArticleId;
      getAllSection();
      getllArticleSort();
      /**
       * 未选中状态 false
       */
    $('#articleName').val(articleName) ;
    $('#articleName').attr('aId',articleId);
    $("#articleType option[value='1']").attr("selected",false);//取消选中 
    $("#articleType option[value='0']").attr("selected",false);//取消选中 
    $("#articleType option[value='"+articleType+"']").attr("selected","selected");//默认选择 
    
    $("#section option[value='"+section.sectionId+"']").attr("selected","selected");//默认选择
    $("#articleSort option[value='"+sortArticleId+"']").attr("selected","selected");//默认选择
    
    
    $("#articleUp option[value='0']").attr("selected",false);//取消选中 
    $("#articleUp option[value='1']").attr("selected",false);//取消选中 
    $("#articleUp option[value='"+articleUp+"']").attr("selected","selected");//默认选择
    
    
    
    $("#articleSupport").attr("checked",false);
    if(articleSupport=="1"){
    $("#articleSupport").attr("checked","checked");}
    
    $('#img').attr('src','/file/image/'+cover);

  })
  .fail(function() {
    console.log("error");
  })
  .always(function() {
    console.log("complete");
  });
  
  
  
}
/**
 * 获取所有版块的信息
 */
function getAllSection(){
	$('#section').html('');
	var getAllSectionURL = getContextPath()+"/front/getallsection";

  $.ajax({
    url: getAllSectionURL,
     async : false, //设置成为 同步的 ,
  })
  .done(function(data) {
    console.log("success");
    var obj=eval("("+data+")"); //转换json
    //alert(obj.sucess==true);
    if(obj.sucess==true){
      var section = obj.section;
      var tempHTML = "";
      $.map(section, function(item, index) {
        tempHTML+="<option value='"+item.sectionId+"'>"+item.sectionName+"</option>"
      });
      $('#section').html(tempHTML);
    }
    console.log(data);
  })
  .fail(function() {
    console.log("error");
  })
  .always(function() {
    console.log("complete");
  });
  
}

/**
 * 获取所有该用户自建的分类
 */
function getllArticleSort(){
	var getAllArticleSortURL =  getContextPath()+"/backStage/getarticlesort";
	$('#articleSort').html('');

  $.ajax({
    url: getAllArticleSortURL,
    async : false//设置成为 同步的
  })
  .done(function(data) {
    console.log("success");
    var obj=eval("("+data+")"); //转换json
    console.log(data);
    articleSort =obj;
    var tempHTML="";
    for(var i = 0; i < obj.length; i++){
      var articlesort =obj[i];
      
      tempHTML+="<option value='"+articlesort.sortArticleId+"'>"+articlesort.sort_article_name+"</option>";
      
    }
    $('#articleSort').html(tempHTML);
  })
  .fail(function() {
    console.log("error");
  })
  .always(function() {
    console.log("complete");
  });
  

	
}


/**bootbox.js
 * 删除单个文章
 */
function delArticle(e){
	
	bootbox.confirm(
            {
                message: "确认要删除吗",
                buttons: {
                    confirm: {
                        label: '确认'
                    },
                    cancel: {
                        label: '取消'
                    }
                },
                callback: function (result) {
                    // 返回 true  或者false
                    if (result) {
                    	var articleId = e.getAttribute("articleId");
                    	  var delArticleURL = getContextPath()+"/article/delArticlebyuserandarticleid";
                    	  $.post(delArticleURL, {'articleId': articleId}, function(data, textStatus, xhr) {
                    	   
                    	    if(data=="1"){bootbox.alert("OK");}
                    	    else{
                    	    	bootbox.alert("errot");
                    	    }
                    	  });
                        
                    } else {
                        bootbox.alert("cancel");
                    }
                }
            });
	
	

	}

/**
 * 获取大部分文章 （分页）
 */
function getArticledtobyuserandpage(){
	var tempHTML =""
  $.post(getContextPath()+"/article/getArticledtobyuserandpage", {"pageSize": pageSize,"currentPage":currentPage}, function(data, textStatus, xhr) {
    /*optional stuff to do after success */
    console.log(data);
    
    var obj=eval("("+data+")"); //转换json
     article = obj.article;
     //开始处理初始化分页
     var page = obj.page;
     totalCount = page.totalCount;
     totalPage  = page.totalPage;
     currentPage = page.currentPage;
     hasPrePage = page.hasPrePage;
     hasNextPage = page.hasNextPage;
     if(hasPrePage==true){
     }
     if(hasNextPage==true){
     }
     $('#totalCount').html('共'+totalCount+'记录    ')
     $('#currentPage').html('当前第 '+currentPage +'页'+'/  ')
      $('#totalPage').html('总共 '+totalPage +'页')
     $('#page').html('<li id="li"><a href="javascript:;" id="hasPrePage" onclick="previousPage()">&laquo;</a></li>')
     for(var i = 1;i<=totalPage;i++){
 		$('.pagination').append('<li><a href="javascript:;" onclick="index('+i+')">'+i+'</a></li>');
 		if(i>9){
 			$('.pagination').append('<li><a href="javascript:;">..</a></li>');
 			break;
 		}
 	}
     $('.pagination').append('<li><a href="javascript:;" id="hasNextPage" onclick="nextPage()">&raquo;</a></li>');
     //处理分页结束
    
     for (var i  = 0; i < article.length;i ++) {
      var user = article[i].user;
      var articleTime = dateFtt('MM-dd-hh:mm:ss',new Date(article[i].articleTime));
      var articleSort = article[i].articleSort;
      var articleType = article[i].articleType;
      var section = article[i].section
      if(articleType=="0"){
    	  articleType = "不公开"
      }else{
    	  articleType = "公开"
      }
    	 tempHTML+="<tr><td>"
       +article[i].articleName+"</td><td>"
       +articleType+"</td><td>"
       +section.sectionName+"</td><td>"
       +articleSort.sort_article_name+"</td><td>"
       +article[i].articleUp+"</td><td>"
       +articleTime+"</td><td>"
       +user.userName+"</td><td>"
       +article[i].articleClick+"</td><td><button id='"
       +article[i].articleId+"' onclick='getSimpleArticle(this)' class='btn btn-primary' data-toggle='modal' data-target='#myModal'>操作</button><a href='javascript:;' onclick='delArticle(this)' articleId='"+
       article[i].articleId+"'>删除</a></td></tr>";
     }
     $('#tbody').html(tempHTML);
  });
	
}

function dateFtt(fmt,date)   
{ //author: meizz   
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}

function getContextPath() { //获取根路径

  var pathName = document.location.pathname;
  var index = pathName.substr(1).indexOf("/");
  var result = pathName.substr(0, index + 1);
  return result;
}

